package com.qlmy.cn.helper.loadsir

import android.view.View
import android.widget.RelativeLayout
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.qlmy.cn.commom.dp

/**
 * Created by zhoucl on 2018/11/26 0026.
 */
object LoadSirHelper {
    fun registerNotDefault(target: Any, callback: Callback? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.let { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun registerMultipleNotDefault(target: Any, callback: MutableList<Callback>? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun register(target: Any, callback: ArrayList<Callback>? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        builder.addCallback(LoadingCallback())
            .addCallback(ErrorCallback())
            .addCallback(EmptyCallback())
            .addCallback(NotNetworkCallback())
            .setDefaultCallback(SuccessCallback::class.java)
        return builder.build().register(target) { listener?.invoke() }
    }

//    fun changePosition(mLoadService: LoadService<*>?, top: Int) {
//        try {
//            mLoadService?.run {
//                setCallBack(EmptyCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_text), top) }
//                setCallBack(LoadingCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_loading), top) }
//                setCallBack(ErrorCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_text), top) }
//            }
//        } catch (e: Exception) {
//            Logger.e(e)
//        }
//    }

    private fun doChangePosition(view: View, top: Int) {
        (view.layoutParams as RelativeLayout.LayoutParams).apply {
            removeRule(RelativeLayout.CENTER_IN_PARENT)
            addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
            topMargin = top.dp
        }
    }
}